package com.ruoyi.system.outto.goods.impl;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.http.HttpUtils;
import com.ruoyi.system.V2.gameAttr.mapper.GameAttributeMapper;
import com.ruoyi.system.V2.goodInfo.mapper.GoodsInfoImgMapper;
import com.ruoyi.system.V2.inter.mapper.ArtRecMapper;
import com.ruoyi.system.model.domain.ArtRec;
import com.ruoyi.system.model.domain.GameAttribute;
import com.ruoyi.system.model.domain.GoodsInfoImg;
import com.ruoyi.system.model.domain.SalePartner;
import com.ruoyi.system.model.dto.GoodsInfoAndAttrValueDto;
import com.ruoyi.system.model.mapper.InfoImgMapper;
import com.ruoyi.system.model.mapper.SuprAuthMapper;
import com.ruoyi.system.outto.core.LCConstant;
import com.ruoyi.system.outto.core.MapUntils;
import com.ruoyi.system.outto.dto.HttpUtil;
import com.ruoyi.system.outto.game.CommonApi;
import com.ruoyi.system.outto.goods.NEWDGUAGUAAPI;
import com.ruoyi.system.outto.goods.NEWLXAPI;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.http.entity.ContentType;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author lz
 * @version 1.0
 * @date 2022/6/5 16:19
 */
@Slf4j
@Service
public class NEWDGUAGUAAPIImpl implements NEWDGUAGUAAPI {

    @Resource
    private InfoImgMapper infoImgMapper;
    @Resource
    private SuprAuthMapper suprAuthMapper;
    @Resource
    private GoodsInfoImgMapper goodsInfoImgMapper;
    @Resource
    private GameAttributeMapper gameAttributeMapper;
    @Resource
    private ArtRecMapper artRecMapper;
    @Resource
    private CommonApi commonApi;
    @Value("${desc.title}")
    private String descTitle;
    private SalePartner salePartner;

    @Override
    public AjaxResult addGame(GoodsInfoAndAttrValueDto goodsInfoAndAttrValueDto, SalePartner salePartner) {
        this.salePartner = salePartner;
        Map<String, Object> params = params(goodsInfoAndAttrValueDto,salePartner);
        Map<String, Object> result = new HashMap<>();
        String response = HttpUtils.sendPost(salePartner.getTwoOther()+"/"+salePartner.getOther()+"/createAccount",JSONObject.toJSONString(params),"application/json");

        log.info("顶呱呱添加接口请求参数={}", JSONObject.toJSONString(params));
        log.info("顶呱呱添加接口返回参数={}", MapUntils.unicodeToString(response));
        JSONObject resultJson = JSONObject.parseObject(response);
        if (!Objects.isNull(resultJson)) {
            if (!"200".equals(resultJson.getString("code"))) {
                result.put("code", 500);
            } else {
                result.put("code", 200);
                ArtRec artRecreq = new ArtRec();
                artRecreq.setConfig(salePartner.getId());
                artRecreq.setAccountId(goodsInfoAndAttrValueDto.getId());
                List<ArtRec> artRecs = artRecMapper.selectArtRecList(artRecreq);
                if (CollectionUtils.isNotEmpty(artRecs)) {
                    artRecs.get(0).setOutid(String.valueOf(goodsInfoAndAttrValueDto.getId()));
                    artRecMapper.updateArtRec(artRecs.get(0));
                } else {
                    artRecreq.setAccountId(goodsInfoAndAttrValueDto.getId());
                    artRecreq.setCreateId(goodsInfoAndAttrValueDto.getCreateId());
                    artRecreq.setType(LCConstant.interAdd);
                    artRecreq.setConfig(salePartner.getId());
                    artRecreq.setSaleCode(salePartner.getSaleName());
                    artRecreq.setOutid(String.valueOf(goodsInfoAndAttrValueDto.getId()));
                    artRecMapper.insertArtRec(artRecreq);
                }
            }
            result.put("msg", resultJson.getString("msg"));
        } else {
            result.put("code", 500);
            result.put("msg", "添加失败");
        }
        result.put("req", JSONObject.toJSONString(params));
        result.put("res", response);
        return AjaxResult.success(result);
    }

    @Override
    public AjaxResult editGame(GoodsInfoAndAttrValueDto goodsInfoAndAttrValueDto, SalePartner salePartner) {
        this.salePartner = salePartner;
        Map<String, Object> result = new HashMap<>();
        //没有编辑接口 先删除再新增
        delGame(goodsInfoAndAttrValueDto,salePartner);
        addGame(goodsInfoAndAttrValueDto,salePartner);
        return AjaxResult.success(result);
    }


    private Map<String, Object> params(GoodsInfoAndAttrValueDto goodsInfoAndAttrValueDto,SalePartner salePartner) {
        Map<String, Object> params = new TreeMap<>();
        params.put("code", goodsInfoAndAttrValueDto.getId().toString());
        BigDecimal bigDecimal = commonApi.addPrice(goodsInfoAndAttrValueDto.getPrice(), salePartner.getSeleep());
        commonApi.setPrice(bigDecimal, goodsInfoAndAttrValueDto.getId(), salePartner);
        params.put("price", bigDecimal.intValue());
        if(StringUtils.isNotEmpty(goodsInfoAndAttrValueDto.getF8())) {
            if(Integer.parseInt(goodsInfoAndAttrValueDto.getF8())>0) {
                params.put("skin_num", Integer.parseInt(goodsInfoAndAttrValueDto.getF8()));
            }else{
                params.put("skin_num", 1);
            }
        }else{
            params.put("skin_num", 1);
        }
        if(StringUtils.isNotEmpty(goodsInfoAndAttrValueDto.getF7())) {
            if(Integer.parseInt(goodsInfoAndAttrValueDto.getF7())>0) {
                params.put("hero_num", Integer.parseInt(goodsInfoAndAttrValueDto.getF7()));
            }else{
                params.put("hero_num", 1);
            }
        }else{
            params.put("hero_num", 1);
        }
        if(StringUtils.isNotEmpty(goodsInfoAndAttrValueDto.getF17())&&!"0".equals(goodsInfoAndAttrValueDto.getF17())) {
            params.put("campID", goodsInfoAndAttrValueDto.getF17());
        }else{
            params.put("campID", "1760376935");
        }
        params.put("service", goodsInfoAndAttrValueDto.getSystemName()+goodsInfoAndAttrValueDto.getCarrierName());
        params.put("is_addiction", 2);
        //写到这了
        if(StringUtils.isNotEmpty(goodsInfoAndAttrValueDto.getF16())) {
            GameAttribute gameAttribute1 = gameAttributeMapper.selectGameAttributeById(Long.valueOf(goodsInfoAndAttrValueDto.getF16()));
            if(gameAttribute1.getFieldName().equals("可二次实名")) {
                params.put("is_real", 1);
            }else{
                params.put("is_real", 2);
            }
        }else{
            params.put("is_real", 2);
        }
        if(StringUtils.isNotEmpty(goodsInfoAndAttrValueDto.getF6())) {
            if(Integer.parseInt(goodsInfoAndAttrValueDto.getF6())>0) {
                params.put("crystal_num", goodsInfoAndAttrValueDto.getF6());
            }else{
                params.put("crystal_num", 1);
            }
        }else{
            params.put("crystal_num", 1);
        }
        if(StringUtils.isNotEmpty(goodsInfoAndAttrValueDto.getF3())) {
            GameAttribute gameAttribute1 = gameAttributeMapper.selectGameAttributeById(Long.valueOf(goodsInfoAndAttrValueDto.getF3()));
            params.put("rank", gameAttribute1.getFieldName());
        }else{
            params.put("rank", "青铜");
        }
        if(StringUtils.isNotEmpty(goodsInfoAndAttrValueDto.getF2())){
            GameAttribute gameAttribute1 = gameAttributeMapper.selectGameAttributeById(Long.valueOf(goodsInfoAndAttrValueDto.getF2()));
            params.put("grade",gameAttribute1.getFieldName());
        }else{
            params.put("grade","V1");
        }
        params.put("highlights",descTitle +"_"+ goodsInfoAndAttrValueDto.getId() +"-"+goodsInfoAndAttrValueDto.getDes().replace("+","").trim());
        String pfIds = "";
        pfIds = reIds(pfIds, goodsInfoAndAttrValueDto.getF9());
        pfIds = reIds(pfIds, goodsInfoAndAttrValueDto.getF10());
        pfIds = reIds(pfIds, goodsInfoAndAttrValueDto.getF11());
        pfIds = reIds(pfIds, goodsInfoAndAttrValueDto.getF12());
        pfIds = reIds(pfIds, goodsInfoAndAttrValueDto.getF15());
        List<GameAttribute> gameAttributes = getGameAttributs(pfIds);
        String pifu = "";
        for(GameAttribute gameAttribute1 : gameAttributes){
            pifu+=","+gameAttribute1.getFieldName();
        }
        if(StringUtils.isNotEmpty(pifu)) {
            params.put("skin_list", pifu.substring(1));
        }else{
            params.put("skin_list", "无");
        }
        String cover = MapUntils.getCover(params);
        String covers = cover.substring(0,cover.length()-1)+salePartner.getSaleKey();
        System.out.println("加密参数==="+covers);
        String sign = DigestUtils.md5Hex(covers);
        params.put("sign",sign);
        return params;
    }

    private List<GameAttribute> getGameAttributs(String ids) {
        List<GameAttribute> list = new ArrayList<>();
        if (StringUtils.isNotEmpty(ids)) {
            list = gameAttributeMapper.selectGameAttributeListByIds((Long[]) ConvertUtils.convert(ids.split(","),
                    Long.class));
        }
        return list;
    }

    private String reIds(String allIds, String ids) {
        if (StringUtils.isNotEmpty(ids)) {
            if (StringUtils.isNotEmpty(allIds)) {
                allIds = allIds + "," + ids;
            } else {
                allIds = ids;
            }
        }
        return allIds;
    }

    @Override
    public AjaxResult delGame(GoodsInfoAndAttrValueDto goodsInfoAndAttrValueDto, SalePartner salePartner) {
        this.salePartner = salePartner;
        Map<String, Object> params = new TreeMap<>();
        Map<String, Object> result = new HashMap<>();
        params.put("code",goodsInfoAndAttrValueDto.getId());
        String cover = MapUntils.getCover(params);
        String covers = cover.substring(0,cover.length()-1)+salePartner.getSaleKey();
        System.out.println("加密参数==="+covers);
        String sign = DigestUtils.md5Hex(covers);
        params.put("sign",sign);
//        String response = HttpUtils.sendPost(salePartner.getTwoOther()+"/seller/{"+salePartner.getOther()+"}/deleteAccount",JSONObject.toJSONString(params),"application/json");
        String response = HttpUtils.sendPost(salePartner.getTwoOther()+"/"+salePartner.getOther()+"/deleteAccount",JSONObject.toJSONString(params),"application/json");
        log.info("顶呱呱删除接口请求参数={}", JSONObject.toJSONString(params));
        log.info("顶呱呱删除接口返回参数={}", response);
        JSONObject resultJson = JSONObject.parseObject(response);
        ArtRec artRecreq = new ArtRec();
        artRecreq.setConfig(salePartner.getId());
        artRecreq.setAccountId(goodsInfoAndAttrValueDto.getId());
        List<ArtRec> artRecs = artRecMapper.selectArtRecList(artRecreq);
        if (!Objects.isNull(resultJson)) {
            if (!"200".equals(resultJson.getString("code"))) {
                result.put("code", 500);
            } else {
                result.put("code", 200);
            }
            result.put("msg", resultJson.getString("msg"));
        } else {
            result.put("code", 500);
            result.put("msg", "删除失败");
        }
        if (CollectionUtils.isNotEmpty(artRecs)) {
            artRecMapper.deleteArtRecById(artRecs.get(0).getId());
        }
        result.put("req", JSONObject.toJSONString(params));
        result.put("res", response);

        return AjaxResult.success(result);
    }

    public static void main(String[] args) {
        Map<String,String> param = new HashMap<>();
        param.put("gameId","3");
        String response = HttpUtil.doGet("http://ff.cyjh.co/api/comm/gamefilter", param, null);
        System.out.println(response);
    }



}
